import React, { useState, useEffect } from 'react';
import { 
  Box, 
  Typography, 
  Paper, 
  Table, 
  TableBody, 
  TableCell, 
  TableContainer, 
  TableHead, 
  TableRow, 
  Button, 
  Chip, 
  CircularProgress, 
  Divider, 
  TextField, 
  IconButton, 
  Tooltip, 
  Accordion, 
  AccordionSummary, 
  AccordionDetails
} from '@mui/material';
import { 
  Download as DownloadIcon, 
  Search as SearchIcon, 
  CalendarToday as CalendarTodayIcon, 
  FileCopy as FileTextIcon, 
  AlertCircle as AlertCircleIcon,
  ExpandMore as ChevronDownIcon,
  FilterList as FilterListIcon,
  Upload as UploadIcon,
  Lock as LockIcon,
  CheckCircle as CheckCircleIcon
} from '@mui/icons-material';
import apiRequest from '../utils/api';
import CryptoJS from 'crypto-js';

const ServiceProviderUserFiles = () => {
  const [userFiles, setUserFiles] = useState([]);
  const [filteredFiles, setFilteredFiles] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedUser, setSelectedUser] = useState('');
  const [showFilters, setShowFilters] = useState(false);
  const [dateRange, setDateRange] = useState({ start: '', end: '' });
  const [fileTypes, setFileTypes] = useState([]);
  const [selectedFileType, setSelectedFileType] = useState('');
  const [users, setUsers] = useState([]);
  
  // 新增状态用于文件上传和密钥处理
  const [dragging, setDragging] = useState(false);
  const [symmetricKey, setSymmetricKey] = useState('');
  const [uploading, setUploading] = useState(false);
  const [uploadedFile, setUploadedFile] = useState(null);
  const [keyValidationError, setKeyValidationError] = useState('');

  // 模拟数据 - 实际项目中应从API获取
  const mockUserFiles = [
    {
      id: 1,
      userId: 101,
      userName: '张三',
      fileName: '车辆维修记录_20240515_张三.xlsx',
      fileType: 'xlsx',
      fileSize: '2.5MB',
      createdAt: '2024-05-15T14:30:00',
      downloadCount: 3,
      encryptionStatus: 'encrypted',
      fileUrl: '/api/download/12345'
    },
    {
      id: 2,
      userId: 102,
      userName: '李四',
      fileName: '车辆维修记录_20240610_李四.pdf',
      fileType: 'pdf',
      fileSize: '4.2MB',
      createdAt: '2024-06-10T09:15:00',
      downloadCount: 1,
      encryptionStatus: 'encrypted',
      fileUrl: '/api/download/12346'
    },
    {
      id: 3,
      userId: 101,
      userName: '张三',
      fileName: '车辆保养提醒_20240720_张三.csv',
      fileType: 'csv',
      fileSize: '0.8MB',
      createdAt: '2024-07-20T16:45:00',
      downloadCount: 2,
      encryptionStatus: 'encrypted',
      fileUrl: '/api/download/12347'
    },
    {
      id: 4,
      userId: 103,
      userName: '王五',
      fileName: '故障诊断报告_20240805_王五.xlsx',
      fileType: 'xlsx',
      fileSize: '3.1MB',
      createdAt: '2024-08-05T11:20:00',
      downloadCount: 0,
      encryptionStatus: 'encrypted',
      fileUrl: '/api/download/12348'
    },
    {
      id: 5,
      userId: 102,
      userName: '李四',
      fileName: '车辆维修记录_20240825_李四.xlsx',
      fileType: 'xlsx',
      fileSize: '2.8MB',
      createdAt: '2024-08-25T15:00:00',
      downloadCount: 1,
      encryptionStatus: 'encrypted',
      fileUrl: '/api/download/12349'
    }
  ];

  // 模拟用户数据
  const mockUsers = [
    { id: 101, name: '张三' },
    { id: 102, name: '李四' },
    { id: 103, name: '王五' }
  ];

  // 加载用户文件列表
  useEffect(() => {
    const loadUserFiles = async () => {
      try {
        setLoading(true);
        setError('');
        
        // 实际项目中，这里应该从API获取数据
        // const response = await apiRequest.get('/api/service-provider/user-files');
        // setUserFiles(response.data);
        
        // 模拟API延迟
        await new Promise(resolve => setTimeout(resolve, 800));
        setUserFiles(mockUserFiles);
        setUsers(mockUsers);
        
        // 提取所有文件类型
        const types = [...new Set(mockUserFiles.map(file => file.fileType))];
        setFileTypes(types);
      } catch (err) {
        setError('加载文件列表失败，请重试');
        console.error('加载用户文件失败:', err);
      } finally {
        setLoading(false);
      }
    };

    loadUserFiles();
  }, []);

  // 应用筛选条件
  useEffect(() => {
    let result = [...userFiles];

    // 按用户名或文件名搜索
    if (searchTerm) {
      const term = searchTerm.toLowerCase();
      result = result.filter(file => 
        file.userName.toLowerCase().includes(term) || 
        file.fileName.toLowerCase().includes(term)
      );
    }

    // 按用户筛选
    if (selectedUser) {
      result = result.filter(file => file.userId.toString() === selectedUser);
    }

    // 按文件类型筛选
    if (selectedFileType) {
      result = result.filter(file => file.fileType === selectedFileType);
    }

    // 按日期范围筛选
    if (dateRange.start) {
      result = result.filter(file => new Date(file.createdAt) >= new Date(dateRange.start));
    }
    if (dateRange.end) {
      result = result.filter(file => new Date(file.createdAt) <= new Date(dateRange.end));
    }

    setFilteredFiles(result);
  }, [userFiles, searchTerm, selectedUser, selectedFileType, dateRange]);

  // 下载文件
  const handleDownload = async (file) => {
    try {
      console.log('下载文件:', file.fileName);
      
      // 根据文件是否已解密来决定下载方式
      if (file.encryptionStatus === 'decrypted' && file.fileUrl && file.fileUrl.startsWith('blob:')) {
        // 对于已解密的文件，使用解密后的Blob URL进行下载
        const link = document.createElement('a');
        link.href = file.fileUrl;
        link.download = file.fileName;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      } else {
        // 对于加密文件或需要从服务器下载的文件，使用模拟的下载方式
        // 实际项目中，这里应该调用API下载文件
        // await apiRequest.get(file.fileUrl, { responseType: 'blob' });
        
        const link = document.createElement('a');
        link.href = URL.createObjectURL(new Blob(['模拟文件内容']));
        link.download = file.fileName;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        URL.revokeObjectURL(link.href);
      }
      
      // 更新下载次数
      setUserFiles(prevFiles => 
        prevFiles.map(f => 
          f.id === file.id ? { ...f, downloadCount: f.downloadCount + 1 } : f
        )
      );
      
    } catch (err) {
      console.error('下载文件失败:', err);
      alert('下载失败，请重试');
    }
  };

  // 重置筛选条件
  const resetFilters = () => {
    setSearchTerm('');
    setSelectedUser('');
    setSelectedFileType('');
    setDateRange({ start: '', end: '' });
  };

  // 格式化日期
  const formatDate = (dateString) => {
    const date = new Date(dateString);
    return new Intl.DateTimeFormat('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    }).format(date);
  };

  // 获取文件类型图标
  const getFileTypeIcon = (fileType) => {
    switch (fileType.toLowerCase()) {
      case 'pdf':
        return <FileTextIcon sx={{ color: '#e02020' }} />;
      case 'xlsx':
      case 'xls':
        return <FileTextIcon sx={{ color: '#2e7d32' }} />;
      case 'csv':
        return <FileTextIcon sx={{ color: '#1565c0' }} />;
      default:
        return <FileTextIcon />;
    }
  };

  // 新增：处理文件拖放事件
  const handleDragOver = (e) => {
    e.preventDefault();
    setDragging(true);
  };

  const handleDragLeave = (e) => {
    e.preventDefault();
    setDragging(false);
  };

  const handleDrop = (e) => {
    e.preventDefault();
    setDragging(false);
    
    if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
      const file = e.dataTransfer.files[0];
      setUploadedFile(file);
    }
  };

  // 手动选择文件
  const handleFileSelect = (e) => {
    if (e.target.files && e.target.files.length > 0) {
      const file = e.target.files[0];
      setUploadedFile(file);
    }
  };

  // 验证128位对称密钥
  const validateSymmetricKey = (key) => {
    // 128位密钥应该是32个十六进制字符 (16字节 × 2字符/字节)
    const hexKeyPattern = /^[0-9a-fA-F]{32}$/;
    return hexKeyPattern.test(key);
  };

  // 处理密钥输入
  const handleKeyChange = (e) => {
    const key = e.target.value;
    setSymmetricKey(key);
    
    if (key && !validateSymmetricKey(key)) {
      setKeyValidationError('密钥必须是32个十六进制字符（128位）');
    } else {
      setKeyValidationError('');
    }
  };

  // 读取文件内容的辅助函数
  const readFileContent = (file) => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = (event) => resolve(event.target.result);
      reader.onerror = (error) => reject(error);
      
      // 对于所有文件，统一使用UTF-8编码读取文本内容
      // 这确保了中文能被正确读取
      reader.readAsText(file, 'UTF-8');
    });
  };
  
  // AES128位解密函数
  const decryptWithAES = (encryptedData, iv, key) => {
    try {
      // 将十六进制密钥转换为WordArray
      const keyWordArray = CryptoJS.enc.Hex.parse(key);
      // 将IV从Base64字符串转换为WordArray
      const ivWordArray = CryptoJS.enc.Base64.parse(iv);
      
      // 使用AES-CBC模式解密
      const decrypted = CryptoJS.AES.decrypt(encryptedData, keyWordArray, {
        iv: ivWordArray,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
      });
      
      // 改进的编码处理方式
      // 1. 先获取解密后的原始二进制数据
      const decryptedBytes = decrypted.toString(CryptoJS.enc.Base64);
      
      // 2. 尝试多种编码方式解码
      let decryptedText;
      
      try {
        // 尝试使用CryptoJS的Utf8解码，添加专门的异常捕获
        try {
          decryptedText = decrypted.toString(CryptoJS.enc.Utf8);
          
          // 检查解密文本是否包含有效字符（包括中文）
          if (decryptedText && decryptedText.length > 0 && /[\x20-\x7E\u4e00-\u9fa5]/.test(decryptedText)) {
            // 验证是否有不可打印的控制字符，如果太多可能表示解码错误
            const controlChars = decryptedText.match(/[\x00-\x1F\x7F]/g) || [];
            if (controlChars.length / decryptedText.length < 0.3) {
              return decryptedText;
            }
          }
        } catch (utf8Error) {
          console.warn('CryptoJS.enc.Utf8解码失败:', utf8Error);
        }
        
        // 如果UTF-8解码结果不理想，尝试使用TextDecoder API（如果支持）
        if (typeof TextDecoder !== 'undefined') {
          try {
            // 将WordArray转换为Uint8Array
            const words = decrypted.words;
            const sigBytes = decrypted.sigBytes;
            const uint8Array = new Uint8Array(sigBytes);
            
            for (let i = 0; i < sigBytes; i++) {
              uint8Array[i] = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
            }
            
            // 使用TextDecoder尝试UTF-8解码
            const decoder = new TextDecoder('utf-8');
            decryptedText = decoder.decode(uint8Array);
            
            if (decryptedText && decryptedText.length > 0 && /[\x20-\x7E\u4e00-\u9fa5]/.test(decryptedText)) {
              return decryptedText;
            }
          } catch (e) {
            console.warn('TextDecoder解码失败:', e);
          }
        }
        
        // 最后尝试Latin1编码作为后备方案
        console.warn('尝试使用Latin1编码作为后备方案');
        decryptedText = decrypted.toString(CryptoJS.enc.Latin1);
        
        return decryptedText;
      } catch (error) {
        console.error('解码失败:', error);
        throw new Error('解密结果无法正确解码，可能是密钥错误或文件格式不匹配');
      }
    } catch (error) {
      console.error('解密过程失败:', error);
      throw error;
    }
  };
  
  // 处理文件上传和密钥解密
  const handleUploadAndDecrypt = async () => {
    if (!uploadedFile) {
      setError('请先选择一个文件');
      setTimeout(() => setError(''), 3000);
      return;
    }

    if (!symmetricKey || !validateSymmetricKey(symmetricKey)) {
      setKeyValidationError('请输入有效的128位对称密钥（32个十六进制字符）');
      return;
    }

    try {
      setUploading(true);
      setError('');
      
      console.log('开始上传并解密文件:', uploadedFile.name, '使用密钥:', symmetricKey);
      
      // 读取文件内容
      const fileContent = await readFileContent(uploadedFile);
      
      // 解析文件内容，提取加密数据和IV
      let encryptedData, iv;
      
      // 检查是否为用户端生成的加密文件格式
      if (fileContent.includes('AES-128-CBC 加密数据')) {
        console.log('识别到用户端生成的加密文件格式');
        
        // 提取IV
        const ivMatch = fileContent.match(/IV:\s*(.+)/);
        if (ivMatch && ivMatch[1]) {
          iv = ivMatch[1];
        } else {
          throw new Error('无法从文件中提取IV');
        }
        
        // 提取加密内容
        const ciphertextMatch = fileContent.match(/加密内容:\s*([\s\S]*)/);
        if (ciphertextMatch && ciphertextMatch[1]) {
          // 移除可能的换行符和空格，获取纯密文
          encryptedData = ciphertextMatch[1].replace(/\s+/g, '');
        } else {
          throw new Error('无法从文件中提取加密内容');
        }
      } else {
        // 尝试其他格式解析
        try {
          // 尝试JSON格式
          const parsedData = JSON.parse(fileContent);
          encryptedData = parsedData.ciphertext;
          iv = parsedData.iv;
        } catch (jsonError) {
          try {
            // 尝试格式: "ciphertext:iv"
            const parts = fileContent.split(':');
            if (parts.length === 2) {
              encryptedData = parts[0];
              iv = parts[1];
            } else {
              // 无法识别的格式
              throw new Error('无法识别的加密文件格式，请确保上传的是用户端生成的加密文件');
            }
          } catch (otherError) {
            throw new Error('无法识别的加密文件格式，请确保上传的是用户端生成的加密文件');
          }
        }
      }
      
      console.log('提取到的IV:', iv);
      console.log('提取到的加密数据长度:', encryptedData.length);
      
      // 执行真实的解密操作
      const decryptedData = decryptWithAES(encryptedData, iv, symmetricKey);
      
      // 创建解密后的文件，确保使用UTF-8编码
      const decryptedBlob = new Blob([decryptedData], { type: 'text/plain;charset=utf-8' });
      const decryptedFileUrl = URL.createObjectURL(decryptedBlob);
      
      // 构造解密后的文件信息
      const decryptedFile = {
        id: Date.now(),
        userId: 100, // 假设是当前服务商用户
        userName: '当前服务商',
        fileName: `解密_${uploadedFile.name.replace('加密', '').replace('.txt', '.txt')}`,
        fileType: 'txt',
        fileSize: `${(decryptedBlob.size / 1024).toFixed(2)}KB`,
        createdAt: new Date().toISOString(),
        downloadCount: 0,
        encryptionStatus: 'decrypted',
        fileUrl: decryptedFileUrl
      };
      
      // 将解密后的文件添加到文件列表
      setUserFiles([decryptedFile, ...userFiles]);
      
      alert(`文件上传并解密成功: ${uploadedFile.name}\n解密后的文件已添加到列表顶部，即将开始下载`);
      
      // 自动下载解密后的文件
      setTimeout(() => {
        handleDownload(decryptedFile);
      }, 1000);
      
      // 重置上传状态
      setUploadedFile(null);
      setSymmetricKey('');
    } catch (err) {
      console.error('文件上传或解密失败:', err);
      setError(err.message || '文件上传或解密失败，请重试');
    } finally {
      setUploading(false);
    }
  };

  return (
    <Box sx={{ p: 3 }}>
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 4 }}>
        <Typography variant="h4">用户文件管理</Typography>
        <Button 
          variant="outlined" 
          color="primary" 
          onClick={() => setShowFilters(!showFilters)}
          startIcon={<FilterListIcon />}
        >
          {showFilters ? '隐藏筛选' : '显示筛选'}
        </Button>
      </Box>

      {/* 新增：文件上传和密钥解密区域 */}
      <Paper 
        elevation={2} 
        sx={{ p: 4, mb: 4, position: 'relative', overflow: 'hidden' }}
        onDragOver={handleDragOver}
        onDragLeave={handleDragLeave}
        onDrop={handleDrop}
      >
        <Box 
          sx={{
            border: `2px dashed ${dragging ? '#1976d2' : '#ccc'}`,
            borderRadius: 2,
            p: 4,
            textAlign: 'center',
            backgroundColor: dragging ? 'rgba(25, 118, 210, 0.05)' : 'transparent',
            transition: 'all 0.2s ease-in-out'
          }}
        >
          <UploadIcon sx={{ fontSize: 48, color: '#1976d2', mb: 2 }} />
          <Typography variant="h6" gutterBottom>导入加密文件</Typography>
          <Typography variant="body2" color="text.secondary" gutterBottom>
            从桌面拖放文件到此处，或点击下方按钮选择文件
          </Typography>
          
          <input
            type="file"
            id="file-upload"
            style={{ display: 'none' }}
            onChange={handleFileSelect}
          />
          <Button 
            variant="outlined" 
            color="primary" 
            component="label"
            startIcon={<FileTextIcon />}
          >
            选择文件
            <input type="file" hidden onChange={handleFileSelect} />
          </Button>
          
          {uploadedFile && (
            <Box sx={{ mt: 2, p: 2, bgcolor: 'background.paper', borderRadius: 1, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <Typography variant="body2">已选择: {uploadedFile.name}</Typography>
              <Chip 
                label={`${(uploadedFile.size / (1024 * 1024)).toFixed(2)} MB`} 
                size="small" 
                color="primary" 
                variant="outlined" 
              />
            </Box>
          )}
        </Box>
        
        {/* 对称密钥输入区域 */}
        <Box sx={{ mt: 4 }}>
          <Typography variant="subtitle1" gutterBottom>128位对称密钥</Typography>
          <TextField
            fullWidth
            label="请输入32个十六进制字符密钥（128位）"
            value={symmetricKey}
            onChange={handleKeyChange}
            error={!!keyValidationError}
            helperText={keyValidationError || "密钥格式应为32个十六进制字符（0-9, a-f）"}
            InputProps={{ startAdornment: <LockIcon size={18} sx={{ mr: 2 }} /> }}
            variant="outlined"
          />
        </Box>
        
        {/* 上传和解密按钮 */}
        <Box sx={{ mt: 4, textAlign: 'center' }}>
          <Button
            variant="contained"
            color="primary"
            onClick={handleUploadAndDecrypt}
            disabled={!uploadedFile || !symmetricKey || !validateSymmetricKey(symmetricKey) || uploading}
            startIcon={uploading ? <CircularProgress size={16} /> : <CheckCircleIcon />}
          >
            {uploading ? '处理中...' : '上传并解密'}
          </Button>
        </Box>
      </Paper>

      {/* 搜索和筛选区域 */}
      <Paper elevation={1} sx={{ p: 3, mb: 4 }}>
        <Box sx={{ display: 'flex', gap: 2, flexWrap: 'wrap', alignItems: 'center' }}>
          <Box sx={{ flex: 1, minWidth: 200 }}>
            <TextField
              fullWidth
              placeholder="搜索用户名或文件名..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              InputProps={{
                startAdornment: <SearchIcon size={18} sx={{ mr: 1 }} />
              }}
            />
          </Box>

          {showFilters && (
            <>
              <Box sx={{ minWidth: 150 }}>
                <TextField
                  fullWidth
                  label="选择用户"
                  select
                  value={selectedUser}
                  onChange={(e) => setSelectedUser(e.target.value)}
                  SelectProps={{ native: true }}
                >
                  <option value="">全部用户</option>
                  {users.map(user => (
                    <option key={user.id} value={user.id}>{user.name}</option>
                  ))}
                </TextField>
              </Box>

              <Box sx={{ minWidth: 120 }}>
                <TextField
                  fullWidth
                  label="文件类型"
                  select
                  value={selectedFileType}
                  onChange={(e) => setSelectedFileType(e.target.value)}
                  SelectProps={{ native: true }}
                >
                  <option value="">全部类型</option>
                  {fileTypes.map(type => (
                    <option key={type} value={type}>{type.toUpperCase()}</option>
                  ))}
                </TextField>
              </Box>

              <Box sx={{ display: 'flex', gap: 2 }}>
                <TextField
                  label="开始日期"
                  type="date"
                  value={dateRange.start}
                  onChange={(e) => setDateRange({...dateRange, start: e.target.value})}
                  InputProps={{ startAdornment: <CalendarTodayIcon size={18} sx={{ mr: 1 }} /> }}
                  InputLabelProps={{ shrink: true }}
                />
                <TextField
                  label="结束日期"
                  type="date"
                  value={dateRange.end}
                  onChange={(e) => setDateRange({...dateRange, end: e.target.value})}
                  InputProps={{ startAdornment: <CalendarTodayIcon size={18} sx={{ mr: 1 }} /> }}
                  InputLabelProps={{ shrink: true }}
                />
              </Box>

              <Button onClick={resetFilters} variant="text" color="secondary">
                重置筛选
              </Button>
            </>
          )}
        </Box>
      </Paper>

      {/* 文件列表 */}
      <Paper elevation={2} sx={{ overflow: 'hidden' }}>
        {loading ? (
          <Box sx={{ display: 'flex', justifyContent: 'center', p: 6 }}>
            <CircularProgress />
          </Box>
        ) : error ? (
          <Box sx={{ display: 'flex', justifyContent: 'center', p: 6, color: 'error.main' }}>
            <Typography variant="h6">{error}</Typography>
          </Box>
        ) : filteredFiles.length === 0 ? (
          <Box sx={{ display: 'flex', justifyContent: 'center', p: 6, color: 'text.secondary' }}>
            <Typography variant="h6">暂无符合条件的文件</Typography>
          </Box>
        ) : (
          <>
            {/* 按用户分组展示文件 */}
            {Array.from(new Set(filteredFiles.map(file => file.userId))).map(userId => {
              const userFiles = filteredFiles.filter(file => file.userId === userId);
              const userName = userFiles[0].userName;
              
              return (
                <Accordion key={userId} defaultExpanded>
                  <AccordionSummary 
                    expandIcon={<ChevronDownIcon />}
                    sx={{ backgroundColor: 'primary.light', color: 'primary.dark' }}
                  >
                    <Typography variant="subtitle1" fontWeight="bold">
                      {userName} - {userFiles.length} 个文件
                    </Typography>
                  </AccordionSummary>
                  <AccordionDetails>
                    <TableContainer>
                      <Table aria-label="用户文件表">
                        <TableHead>
                          <TableRow sx={{ backgroundColor: 'grey.100' }}>
                            <TableCell>文件名</TableCell>
                            <TableCell>文件类型</TableCell>
                            <TableCell>文件大小</TableCell>
                            <TableCell>创建时间</TableCell>
                            <TableCell>下载次数</TableCell>
                            <TableCell>加密状态</TableCell>
                            <TableCell align="right">操作</TableCell>
                          </TableRow>
                        </TableHead>
                        <TableBody>
                          {userFiles.map((file) => (
                            <TableRow key={file.id} hover>
                              <TableCell>
                                <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
                                  {getFileTypeIcon(file.fileType)}
                                  <span>{file.fileName}</span>
                                </Box>
                              </TableCell>
                              <TableCell>
                                <Chip 
                                  label={file.fileType.toUpperCase()} 
                                  size="small"
                                  color={
                                    file.fileType === 'pdf' ? 'error' : 
                                    file.fileType === 'xlsx' ? 'success' : 'primary'
                                  }
                                />
                              </TableCell>
                              <TableCell>{file.fileSize}</TableCell>
                              <TableCell>{formatDate(file.createdAt)}</TableCell>
                              <TableCell>{file.downloadCount}</TableCell>
                              <TableCell>
                                <Chip 
                                  label={file.encryptionStatus === 'encrypted' ? '已加密' : '未加密'}
                                  size="small"
                                  color={file.encryptionStatus === 'encrypted' ? 'success' : 'warning'}
                                />
                              </TableCell>
                              <TableCell align="right">
                                <Tooltip title="下载文件">
                                  <IconButton 
                                    onClick={() => handleDownload(file)}
                                    color="primary"
                                    size="small"
                                  >
                                    <DownloadIcon size={18} />
                                  </IconButton>
                                </Tooltip>
                              </TableCell>
                            </TableRow>
                          ))}
                        </TableBody>
                      </Table>
                    </TableContainer>
                  </AccordionDetails>
                </Accordion>
              );
            })}
          </>
        )}
      </Paper>

      {/* 文件统计信息 */}
      {!loading && !error && (
        <Box sx={{ mt: 4, p: 2, bgcolor: 'background.paper', borderRadius: 2 }}>
          <Typography variant="body2" color="text.secondary">
            总计: {filteredFiles.length} 个文件 | 
            用户数量: {Array.from(new Set(filteredFiles.map(file => file.userId))).length} | 
            下载次数总计: {filteredFiles.reduce((sum, file) => sum + file.downloadCount, 0)}
          </Typography>
        </Box>
      )}
    </Box>
  );
};

export default ServiceProviderUserFiles;